﻿using Microsoft.EntityFrameworkCore;
using Redis实战.Data;
using Redis实战.Interface;
using Redis实战.Models;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Redis实战.Services
{
    public class UserRepository : IUserRepository
    {
        private readonly AppDbContext _dbContext;

        // 注入数据库上下文
        public UserRepository(AppDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<User?> GetByIdAsync(int id, CancellationToken cancellationToken = default)
        {
            // 从数据库查询
            return await _dbContext.Users.FindAsync(new object[] { id }, cancellationToken);
        }

        public async Task UpdateAsync(User user, CancellationToken cancellationToken = default)
        {
            _dbContext.Users.Update(user);
            user.LastUpdated = DateTime.UtcNow; // 更新时间戳
            await _dbContext.SaveChangesAsync(cancellationToken);
        }

        public async Task CreateAsync(User user, CancellationToken cancellationToken = default)
        {
            user.LastUpdated = DateTime.UtcNow; // 设置创建时间
            await _dbContext.Users.AddAsync(user, cancellationToken);
            await _dbContext.SaveChangesAsync(cancellationToken);
        }

        // 修复：添加CancellationToken参数，与服务层调用匹配
        public async Task DeleteAsync(int id, CancellationToken cancellationToken = default)
        {
            var user = await _dbContext.Users.FindAsync(new object[] { id }, cancellationToken);
            if (user == null)
            {
                throw new KeyNotFoundException($"用户ID {id} 不存在");
            }
            _dbContext.Users.Remove(user);
            await _dbContext.SaveChangesAsync(cancellationToken); // 传递取消令牌
        }

        // 缓存清除方法（保持接口实现，实际逻辑在缓存服务）
        public Task RemoveUserCacheAsync(int id)
        {
            throw new NotImplementedException("缓存清除逻辑应在RedisCacheService中实现");
        }
    }
}
